<template>
  <el-form ref="formRef" :model="form" :rules="rules" :show-message="false" label-width="100px" size="default" label-suffix="：">
    <el-row>
      <el-col :span="24">
        <el-form-item label="参数名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入参数名称"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="参数键名" prop="id">
          <el-input v-model="form.id" placeholder="请输入参数键名"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="参数键值" prop="value">
          <el-input v-model="form.value" placeholder="请输入参数键值"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="系统内置">
          <el-radio-group :disabled="! isAdd" v-model="form.type">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="备注">
          <el-input
              v-model="form.remark"
              :rows="3"
              type="textarea"
              placeholder="请输入备注"
          />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script setup name="x-form">
import useStore from '@/stores/modules/sys/parameter';
const parameter = useStore();
const formRef = ref()

import {reactive, ref} from "vue";

let isAdd = ref(true)

const form = reactive({
  name: "",
  id: "",
  value: "",
  type: 0,
  remark: ""
})

const rules = ref({
  name: { required: true, message: '参数名称不能为空', trigger: 'click'},
  id: { required: true, message: '参数键名不能为空', trigger: 'click'},
  value: { required: true, message: '参数键值不能为空', trigger: 'click'},
})

/**
 * 表单验证
 * @param callback
 * @returns {Promise<void>}
 */
const doValidate = async (callback) => {
  await formRef.value.validate((valid, fields) => {
    if (! valid) {
      let errMsg = Helper.getFirstMessage(fields);
      if (errMsg) {
        Msg.error(errMsg)
      }
      callback(false)
      return
    }

    callback(form)
  })
}

/**
 * 保存
 * @returns {Promise<void>}
 */
const submit = async () => {
  await doValidate(async (form) => {
    if (form == false) {
      return
    }

    let result = null
    result = isAdd.value ? await parameter.add(form) : await parameter.modify(form)
    if (result) {
      Dialog.close()
    }
  })
}

/**
 * 获取数据
 * @param data
 */
const render = (data) => {
  isAdd.value = Helper.emptyJson(data)

  if (! isAdd.value) {
    for (let key in data) {
      form[key] = data[key]
    }
  }
}

defineExpose({ render, submit })
</script>